const puppeteer = require("puppeteer");
const { tasks, pathToChrome } = require("./config.js");

// 封装访问 + 滚动函数
async function visitAndScroll(browser, url, index, visitCount) {
  for (let i = 1; i <= visitCount; i++) {
    const page = await browser.newPage();
    console.log(`第 ${index} 个页面，第 ${i} 次访问: ${url}`);

    try {
      await page.goto(url, {
        waitUntil: "networkidle2",
        timeout: 60000,
      });

      // 模拟滚动到底部
      await page.evaluate(async () => {
        await new Promise((resolve) => {
          let totalHeight = 0;
          const distance = 100;
          const timer = setInterval(() => {
            const scrollHeight = document.body.scrollHeight;
            window.scrollBy(0, distance);
            totalHeight += distance;

            if (totalHeight >= scrollHeight) {
              clearInterval(timer);
              resolve();
            }
          }, 100);
        });
      });

      // 停顿 2 秒
      await new Promise((resolve) => setTimeout(resolve, 1000));
    } catch (err) {
      console.error(`访问失败: ${url}`, err);
    } finally {
      await page.close();
    }

    // 每次访问间隔：随机 5 到 15 秒
    if (i < visitCount) {
      const randomDelay = Math.floor(Math.random() * 10000) + 5000; // 5-15秒之间
      console.log(`等待 ${randomDelay / 1000} 秒...`);
      await new Promise((resolve) => setTimeout(resolve, randomDelay)); // 随机延迟
    }
  }
}

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    defaultViewport: null,
    executablePath: pathToChrome,
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });

  for (let i = 0; i < tasks.length; i++) {
    const { url, times } = tasks[i];
    await visitAndScroll(browser, url, i + 1, times);
  }

  await browser.close();
})();
